import {Component, OnInit} from '@angular/core';
import {DataService} from '../data.service';
import {Router} from '@angular/router';
import {NzNotificationService} from 'ng-zorro-antd';

declare const $: any;
@Component({
  selector: 'app-configtable',
  templateUrl: './configtable.component.html',
  styleUrls: ['./configtable.component.css']
})
export class ConfigtableComponent implements OnInit {


  config_all = [];
  config = [];

  room = [
    {
      num: '全部',
      desc: '空调房'
    }
  ];
  priority = {value: 'low', label: 'low'};

  priority_options = [
    { value: 'low', label: 'low' },
    { value: 'medium', label: 'medium' },
    { value: 'high', label: 'high'}
  ];

  type_options = [
    { value: '开关', label: '开关'},
    { value: '空调', label: '空调' },
    { value: '地暖', label: '地暖' },
    { value: '调光', label: '调光'},
    { value: '音乐播放器', label: '音乐播放器'},
  ];

  data_options = [
    { value: '1bit', label: '1bit' },
    { value: '1字节', label: '1字节' },
    { value: '2字节', label: '2字节'}
  ];

  selected_priority = this.priority_options[ 0 ];
  selected_type = this.type_options[ 0 ];
  selected_data = this.data_options[0];

  is_new_controller = false;
  is_modify_controller = false;
  // is_new_room = false;

  checked_config: any;

  new_controller = { // 缓存要添加的控件，用完记得清空
    project_id: 0,
    type: '',
    name: '' ,
    address : '',
    data_type : '',
    value: 0,
    room : 0,
    room_desc: '',
    priority: '',
  };

  modifying = {  // 缓存要修改/删除的控件，用完记得清空
    project_id: 0,
    id: '',
    type: '',
    name: '' ,
    address : '',
    data_type : '',
    value: 0,
    room : 0,
    room_desc: '',
    priority: '',
    delete_arr: [],
  };

  // new_room = {
  //   num: '0',
  //   desc: '',
  // };

  _allChecked = false;
  _checkedNumber = 0;
  _displayData: Array<any> = [];
  _indeterminate = false;


  add_controller_url = 'http://localhost/backend/add_controller.php';
  change_controller_url = 'http://localhost/backend/change_controller.php';
  delete_controller_url = 'http://localhost/backend/delete_controller.php';
  import_controller_url = 'http://localhost/backend/import_controller.php';
  // import_controller_url = 'http://localhost/backend/test.php';
  export_controller_url = 'http://localhost/backend/export_controller.php';
  export_esf_url = 'http://localhost/backend/export_esf.php';

  constructor(private data: DataService, private route: Router, private _notification: NzNotificationService) { }

  ngOnInit() {
    this.data.edit_project_id =  parseInt($.cookie('edit_project_id'));
    if (this.data.edit_project_id == 0 || this.data.edit_project_id == undefined) {
      this.route.navigate(['/project']);
    }
    this.config_all = this.data.get_controller(this.data.edit_project_id);
    this.config = this.config_all;
    this.init_room();
  }



  init_room() {
    const room_list = [];
    const room_desc_list = [];

    for (let i in this.config){
      if (room_list.indexOf(this.config[i].room) == -1) {
        room_list.push(this.config[i].room);
        room_desc_list.push(this.config[i].room_desc);
      }
    }
    for (let j = 0; j < room_list.length; j++) {
      this.room.push({
        num: room_list[j],
        desc: room_desc_list[j]
      });
    }
  }

  refresh_table(tab) {
    const config_list = [];
    if (tab.num != '全部'){
      for (let i in this.config_all) {
        if (tab.num == this.config_all[i].room) {
          config_list.push(this.config_all[i]);
        }
      }
      setTimeout( () => {
        this.config = config_list;
        // console.log(this.config);
      } , 200);

    } else {
      setTimeout( () => {
      this.config = this.config_all;
      } , 200);
    }
  }



  show_modal(modal) {   // 显示模态框并获取模态框显示的数据
    if (modal == 'controller') {
      this.is_new_controller = true;
    } else if (modal == 'modify') {
      this.is_modify_controller = true;
      this.modifying = this.checked_config[0];
      // console.log(this.modifying);
      this.selected_type.value = this.checked_config[0].type;
      this.selected_type.label = this.checked_config[0].type;
      this.selected_data.value = this.checked_config[0].data_type;
      this.selected_data.label = this.checked_config[0].data_type;
      this.selected_priority.value = this.checked_config[0].priority;
      this.selected_priority.label = this.checked_config[0].priority;
      // console.log(this.selected_type);
      // console.log(this.selected_data);
      // console.log(this.selected_priority);
    }
  }

  cancel_modal(modal) {  // 关闭模态框并且清空缓存
    if (modal == 'controller') {
      this.is_new_controller = false;
      this.new_controller = {
        project_id: 0,
        type: '',
        name: '' ,
        address : '',
        data_type : '',
        value: 0,
        room : 0,
        room_desc: '',
        priority: '',
      };
    } else if (modal == 'modify') {
      this.is_modify_controller = false;
      this.modifying = {  // 传完清空缓存
        project_id: 0,
        id: '',
        type: '',
        name: '' ,
        address : '',
        data_type : '',
        value: 0,
        room : 0,
        room_desc: '',
        priority: '',
        delete_arr: [],
      };
    }
  }

  add_controller() {  // 添加控件
    this.new_controller.type = this.selected_type.value;
    this.new_controller.data_type = this.selected_data.value;
    this.new_controller.priority = this.selected_priority.value;
    this.new_controller.project_id = this.data.edit_project_id;
    this.data.post(this.new_controller , this.add_controller_url);
    this.new_controller = {  // 传完清空缓存
      project_id: 0,
      type: '',
      name: '' ,
      address : '',
      data_type : '',
      value: 0,
      room : 0,
      room_desc: '',
      priority: '',
    };
    this.is_new_controller = false;
    location.reload();
  }

  change_controller() {  // 修改控件
    this.modifying.type = this.selected_type.value;
    this.modifying.data_type = this.selected_data.value;
    this.modifying.priority = this.selected_priority.value;
    this.modifying.project_id = this.data.edit_project_id;
    this.data.post(this.modifying, this.change_controller_url);
    this.modifying = {  // 传完清空缓存
      project_id: 0,
      id: '',
      type: '',
      name: '' ,
      address : '',
      data_type : '',
      value: 0,
      room : 0,
      room_desc: '',
      priority: '',
      delete_arr: [],
    };
    this.is_modify_controller = false;
  }

  delete_config() {
    for (let i = 0; i < this.checked_config.length; i++) {
      this.modifying.project_id = this.data.edit_project_id;
      this.modifying.delete_arr.push(this.checked_config[i].id);
    }
    this.data.post(this.modifying , this.delete_controller_url);
    // console.log(this.modifying.delete_arr);
    this.modifying.delete_arr = [];
    location.reload();
  }

  cancel_delete() {
    this.modifying.delete_arr = [];
  }


  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~import & export~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  import_controller() {
    let up_file = $('#file').get(0).files[0];
    let form_data = new FormData();
    // console.log(this.data.edit_project_id);
    form_data.append('controller_file', up_file);
    form_data.append('edit_project_id', this.data.edit_project_id.toString());
    // console.log(form_data);
    $.ajax({
      type: 'POST',
      url: this.import_controller_url,
      contentType: false,
      processData: false,
      async: false,
      data: form_data,
      error: function () {
        alert('无法读取文件');
      },
      success: (data) => {
        console.log('文件读取成功');
        console.log(data);
      }
    });
    location.reload();
  }

  export_controller() {
    // console.log(this.config_all);
    this.data.post({'data': this.config_all}, this.export_controller_url);  // 传的值强行变成键值对
    if (this.data.import_success) {  // 这个变量只用来控制通知框
       this._notification.blank('导出成功', '文件地址:' + '/backend/project');
       this.data.import_success = false;
     }
  }

  export_esf() {
    this.data.post({'id': this.data.edit_project_id, 'data': this.config_all}, this.export_esf_url);  // 传的值强行变成键值对
    if (this.data.import_success) {  // 这个变量只用来控制通知框
      this._notification.blank('导出成功', '文件地址:' + '/backend/project');
      this.data.import_success = false;
    }
  }


  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~table~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  _displayDataChange($event) {
    this._displayData = $event;
  }

  _refreshStatus() {
    const allChecked = this._displayData.every(value => value.checked === true);
    const allUnChecked = this._displayData.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
    this._checkedNumber = this.config.filter(value => value.checked).length;
    this.checked_config = this.config.filter(value => value.checked);
    // console.log(this.checked_config);
  }

  _checkAll(value) {
    if (value) {
      this._displayData.forEach(data => data.checked = true);
    } else {
      this._displayData.forEach(data => data.checked = false);
    }
    this._refreshStatus();
  }


}
